﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace HospitalSystem.Admin
{
    public partial class Login : System.Web.UI.Page
    {
        public static string key = "MDCODE";//can change
        public string role = "Norole";
        public string activated = "Null";
        string strConnString = ConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void sendsession()
        {
            Session["idlogin"] = UsernameTextBox.Text;


            //  Response.Redirect("~/diagnosemedical.aspx");



        }



        private void checkmutirole()
        {

            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString;
            SqlConnection scon = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand("SELECT count([Role_id]) as id FROM [Role_Staff] where Staff_id=@CID", scon);
            cmd.Parameters.AddWithValue("@CID", Session["idlogin"]);

            scon.Open();
            object triggerCount = cmd.ExecuteScalar();



            if ((int)triggerCount == 1)
            {

            }

            else

            {
                Response.Redirect("~/mutirole.aspx");
            
            }
            scon.Close();
        }


        private void MessageBox(string msg)
        {
            Label lbl = new Label();
            lbl.Text = "<script language='javascript'>" + Environment.NewLine + "window.alert('" + msg + "')</script>";
            Page.Controls.Add(lbl);
        }
        private void MyTicket(string p, string myrole)
        {
            FormsAuthenticationTicket myticket = new FormsAuthenticationTicket(1, p, DateTime.Now, DateTime.Now.AddMinutes(2), true, myrole); //เริ่มสร้าง ticket  ในเวลาปัจจุบันและให้ ticket นีมีอายุ 2 นาที
            string encrptyticket = FormsAuthentication.Encrypt(myticket);
            HttpCookie mycookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrptyticket);
            if (myticket.IsPersistent)
            {
                mycookie.Expires = myticket.Expiration; //ให้  cookie หมดอายุตาม เวลาที่  ticket หมดอายุ
                Response.Cookies.Add(mycookie);
                if (myrole == "1") //ถ้า role = 1 SystemAdmin
                {
                    sendsession();

                    checkmutirole();
                    Response.Redirect("~/Admin/AdminManagement.aspx");
                }
                else if (myrole == "2")//ถ้า role = 2 ครุูพี่เลี้ยง
                {
                    sendsession();
                    checkmutirole();
                    Response.Redirect("~/index.aspx");
                }
                else if (myrole == "3")//ถ้า role = 3 CostAdmin
                {
                    sendsession();
                    checkmutirole();
                    Response.Redirect("~/Finance.aspx");
                }
                else if (myrole == "4")//ถ้า role = OT
                {
                    sendsession();
                    Response.Redirect("~/OThomepage.aspx");
                }
                else if (myrole == "5")//ถ้า role = PT
                {
                    sendsession();
                    Response.Redirect("~/OThomepage.aspx");
                }
                else if (myrole == "6")//ถ้า role =6 Prosthetis/Orthotist
                {
                    sendsession();
                    Response.Redirect("~/OThomepage.aspx");
                }
                else if (myrole == "7")//ถ้า role = 7 nurse
                {
                    sendsession();
                    Response.Redirect("~/Nurse/NurseHomepage.aspx");
                }
                else if (myrole == "8")//ถ้า role = 8 Accountant
                {
                    sendsession();
                    Response.Redirect("~/Accountant/acthome.aspx");
                }
                else if (myrole == "9")//ถ้า role = 9 GeneralDoctor
                {
                    sendsession();
                    Response.Redirect("~/OThomepage.aspx");
                }
                
            }

        }
        private string CheckRole(string u, string p)
        {
            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString; // เรียกใช้ connectionstring จาก webconfig
            string comstr = "SELECT Role_id AS 'role id' FROM Role_Staff WHERE Staff_id IN(SELECT Staff_id FROM Employee WHERE Username = @username AND Password = @password)"; // ดึงค่าของ roleID ตาม username,password
            SqlConnection con = new SqlConnection(constr);
            SqlCommand com = new SqlCommand(comstr, con);
            SqlParameter param1, param2;
            param1 = new SqlParameter();
            param1.ParameterName = "@username";
            param1.SqlDbType = SqlDbType.NVarChar;
            param1.Value = u;
            param2 = new SqlParameter();
            param2.ParameterName = "@password";
            param2.SqlDbType = SqlDbType.NVarChar;
            param2.Value = p;
            SqlParameter[] allparam = { param1, param2 };
            com.Parameters.AddRange(allparam);
            com.Connection.Open();
            SqlDataReader reader = com.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                role = reader.GetInt32(0).ToString();
                break;
            }
            com.Connection.Close();
            return role;
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
           
            
            string Password = Encrypt(PasswordTextBox.Text, key);
            string myrole = CheckRole(UsernameTextBox.Text, Password);
            string IsActivated = CheckPerMission(UsernameTextBox.Text, Password);
            if (IsActivated == "1")
            {
                if (myrole == "Norole")//ตรวจสอบ role ที่ได้รับมาจากเมธอดว่า เป็น  Norole หรือไม่
                {
                    MessageBox("InvalidPassword");
                    return;
                }
                else //ถ้าไม่เป็น Norole ก็ให้สร้าง Ticket  (Ticket ก็เหมือนกับใบผ่านทางของ user สำหรับเข้าหน้าอื่นๆได้โดยบอกว่า user นี้มี role อะไรจะเข้าหน้าไหนได้บ้าง)
                {
                    MyTicket(UsernameTextBox.Text, myrole);
                }
            }
            else if (IsActivated == "0")
            {
                MessageBox("ID Status : รอการรับรองจากทางระบบ");
            }
            else
            {
                MessageBox("ID Status : Username นี้ ไม่ได้รับการรับรองจากระบบหรือไม่มีอยู่ในระบบ");
            }
        }
        public string Encrypt(string strToEncrypt, string strKey)
        {
            try
            {
                TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

                byte[] byteHash, byteBuff;
                string strTempKey = strKey;

                byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
                objHashMD5 = null;
                objDESCrypto.Key = byteHash;
                objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

                byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
                return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
            }
            catch (Exception ex)
            {
                return "Wrong Input. " + ex.Message;
            }
        }

        public string Decrypt(string strEncrypted, string strKey)
        {
            try
            {
                TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
                MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

                byte[] byteHash, byteBuff;
                string strTempKey = strKey;

                byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
                objHashMD5 = null;
                objDESCrypto.Key = byteHash;
                objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

                byteBuff = Convert.FromBase64String(strEncrypted);
                string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
                objDESCrypto = null;

                return strDecrypted;
            }
            catch (Exception ex)
            {
                return "Wrong Input. " + ex.Message;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/ForgetPassword.aspx");
        }

        private string CheckPerMission(string u, string p)
        {
            string constr = WebConfigurationManager.ConnectionStrings["strconnection"].ConnectionString; // เรียกใช้ connectionstring จาก webconfig
            string comstr = "SELECT Activated FROM Employee WHERE Staff_id IN(SELECT Staff_id FROM Employee WHERE Username = @username AND Password = @password)"; // ดึงค่าของ roleID ตาม username,password
            SqlConnection con = new SqlConnection(constr);
            SqlCommand com = new SqlCommand(comstr, con);
            SqlParameter param1, param2;
            param1 = new SqlParameter();
            param1.ParameterName = "@username";
            param1.SqlDbType = SqlDbType.NVarChar;
            param1.Value = u;
            param2 = new SqlParameter();
            param2.ParameterName = "@password";
            param2.SqlDbType = SqlDbType.NVarChar;
            param2.Value = p;
            SqlParameter[] allparam = { param1, param2 };
            com.Parameters.AddRange(allparam);
            com.Connection.Open();
            SqlDataReader reader = com.ExecuteReader(CommandBehavior.CloseConnection);
            while (reader.Read())
            {
                activated = reader.GetValue(0).ToString();
                break;
            }
            com.Connection.Close();
            return activated;
        }
    }
}